package com.tedu.springboot2302.controller;

import com.tedu.springboot2302.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @author Huangjin
 * @version 1.0
 * describe:
 * @date 2023/3/17 17:25
 */
@Controller
public class ArticleController {
    private static File articleDir;
    static {
        articleDir = new File("./articles");
        if(!articleDir.exists()){
            articleDir.mkdirs();
        }
    }
    @RequestMapping("/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理发表文章功能！！！");
        //获取表单信息
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String author = request.getParameter("author");
        System.out.println(0);
        //对提交的数据进行验证
        if (title==null||title.isEmpty()||
                content==null||content.isEmpty()||
                author==null||author.isEmpty()){
            //直接给一个相应错误的页面
            try {
                response.sendRedirect("/article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;//跳到这里便不再执行
        }

        //第一个参数的File对象表示当前文件在哪个目录中
        File file = new File(articleDir,title+".obj");
        //首先判断改文件是否已经存在，存在则说明此为重复文章
        /*if (file.exists()) {
            try {
                response.sendRedirect("/writeArticle.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }*/
        //序列化
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos);)
        {
            oos.writeObject(title);
            response.sendRedirect("/article_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
